package cn.topca.grame

import com.vshining.grame.Menu

class GMenuTagLib {
    static namespace = "menu"
    def levelMenu = { attr, body ->
        if (attr.level) {
            int menuLevel = Integer.parseInt(attr.level);
            def menus = Menu.createCriteria().list {
                order('index', 'aes')
                eq('level', menuLevel)
                isNull('preMenu')
            }
            PrintWriter writer = new PrintWriter(out);
            writer.println raw("<ul class=\"menu level_${menuLevel}\">")
            for (Menu gMenu : menus) {
                indent(1, writer)
                writer.println raw("<li${gMenu.subMenus ? ' class="menu_group"' : ''}>")
                indent(2, writer)
                writer.print raw("<a href=\"")
                writer.print menuTarget2Url(gMenu.target)
                writer.print "\">"
                writer.print gMenu.name
                writer.println raw("</a>")
                if (gMenu.subMenus.size() > 0) {
                    indent(2, writer)
                    writer.println raw('<ul class="menu_group_item">')
                    for (Menu gMenu1 : gMenu.subMenus) {
                        indent(3, writer)
                        writer.println raw('<li>')
                        indent(4, writer)
                        writer.print raw("<a href=\"")
                        writer.print menuTarget2Url(gMenu1.target)
                        writer.print "\">"
                        writer.print gMenu1.name
                        writer.println raw("</a>")
                        indent(3, writer)
                        writer.println raw('</li>')
                    }
                    indent(2, writer)
                    writer.println raw('</ul>')
                }
                indent(1, writer)
                writer.println raw('</li>')
            }
            writer.println raw('</ul>')
        }
    }

    private String menuTarget2Url(String target = "#") {
        String url
        if (target.startsWith('grails:controllers:')) {
            String controller = target.split(':')[2]
            String action = target.split(':')[3]
            url = createLink(controller: controller, action: action);
        } else if (target.startsWith('grails:uri:')) {
            String grailsUri = target.split(':')[2]
            url = createLink(uri: grailsUri)
        } else {
            url = createLink(url: target)
        }
        return url
    }

    private void indent(int level, Writer writer) {
        for (int i = 0; i < level; i++) {
            writer.append('\t')
        }
    }
}
